package com.icebergteam.warfacewidget.news.ui;

import java.util.ArrayList;
import java.util.Locale;
import com.icebergteam.warfacewidget.AppManager;
import com.icebergteam.warfacewidget.WidgetApplication;
import com.icebergteam.warfacewidget.WidgetProvider;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.utils.TimeDateUtils;
import com.icebergteam.warfacewidget.core.utils.ViewUtils;
import com.icebergteam.warfacewidget.data.sql.NewsTable;
import com.icebergteam.warfacewidget.news.data.NewsItem;
import com.icebergteam.warfacewidget.ui.AdBannerFragment;
import com.icebergteam.warfacewidget.R;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ShareActionProvider;
import android.widget.ShareActionProvider.OnShareTargetSelectedListener;
import android.widget.TextView;
import android.widget.Toast;

public class NewsActivity extends FragmentActivity implements OnShareTargetSelectedListener{
	public static String className = NewsActivity.class.getCanonicalName();
	public static final String KEY_HEIGHT_ACTION_BAR = String.format(
			"%s.KEY_HEIGHT_ACTION_BAR", className);

	private ViewPager pager;
	private TextView pageText;
	private ScreenSlidePagerAdapter pagerAdapter;
	private ArrayList<NewsItem> parNewsListArray;
	private int heightActionBar = 96;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		try {
			// FIXME:remove it for force localized title activity
			this.setTitle(R.string.news_activity_title);
			setContentView(R.layout.news_activity);
	
			if (savedInstanceState != null) {
					this.heightActionBar = savedInstanceState
						.getInt(NewsActivity.KEY_HEIGHT_ACTION_BAR);
			} 
			Cursor cursor = AppManager.getDatabase().getNewsTable().getNews(null/*AppManager.getNewsSettings().getCategories()*/);
											
			parNewsListArray = new ArrayList<NewsItem>();
			while(cursor!= null && cursor.moveToNext()){
				NewsItem item = new NewsItem();
				item.setId(cursor.getInt(cursor.getColumnIndex(NewsTable.FIELD_ID.trim())));
				item.setTitle(cursor.getString(cursor.getColumnIndex(NewsTable.FIELD_TITLE.trim())));
				item.setDesc(cursor.getString(cursor.getColumnIndex(NewsTable.FIELD_DESC.trim())));
				item.setImgSrc(cursor.getString(cursor.getColumnIndex(NewsTable.FIELD_IMGSRC.trim())));
				item.setPubdate(cursor.getLong(cursor.getColumnIndex(NewsTable.FIELD_PUBDATE.trim())));
				item.setLink(cursor.getString(cursor.getColumnIndex(NewsTable.FIELD_URL.trim())));
				item.setRead(cursor.getInt(cursor.getColumnIndex(NewsTable.FIELD_READ.trim())));
					
				parNewsListArray.add(item);
			}
			cursor.close();
			if(parNewsListArray.isEmpty()){
				throw new Exception(LogManager.getLogMessage(LogManager.getExecuteMethodName(), "empty news array"));
			}
				// Initiate a generic request to load it with an ad
			pageText = (TextView) findViewById(R.id.news_activity_pageIndicator_TextView);
	
			pager = (ViewPager) findViewById(R.id.news_activity_pager_ViewPager);
			pagerAdapter = new ScreenSlidePagerAdapter(
					this.getSupportFragmentManager(), parNewsListArray);
	
			pager.setAdapter(pagerAdapter);
			
			int currentItemIndex = getIntent().getExtras().getInt(
					NewsListViewFactory.POS_INTENT_KEY);
			
			
			pager.setCurrentItem(currentItemIndex);
			updatePagerText();
			
			pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
				@Override
				public void onPageSelected(int position) {
					updatePagerText();
					invalidateOptionsMenu();
					try {
						setReadNews(position);
					} catch (Exception e) {
						LogManager.LogEA(className, "error set read");
						Toast.makeText(NewsActivity.this, NewsActivity.this.getString(R.string.not_found_current_news_removed), Toast.LENGTH_LONG).show();
					}
				}
			});
			pager.offsetLeftAndRight(2);
//			pager.setPageTransformer(true, new DepthPageTransformer());
//			pager.setPageTransformer(true, new ZoomOutPageTransformer());
			AdBannerFragment.setBanner(this, savedInstanceState, R.id.news_activity_adbanner_layout);
		
		} catch (Exception e) {
			LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
			Toast.makeText(this, this.getString(R.string.request_failed_restored_failed), Toast.LENGTH_LONG).show();
		}
	}
	
	void setReadNews(int pos) throws Exception{
		NewsItem item = parNewsListArray.get(pos);
		if(item!= null && !item.isRead() && pos == pager.getCurrentItem()){
			AppManager.getDatabase().getNewsTable().setReadNews(item.getLink());
			
		}
	}
	
	public class ZoomOutPageTransformer implements ViewPager.PageTransformer {
	    private static final float MIN_SCALE = 0.96f;
	    private static final float MIN_ALPHA = 0.8f;

	    public void transformPage(View view, float position) {
	        int pageWidth = view.getWidth();
	        int pageHeight = view.getHeight();

	        if (position < -1) { // [-Infinity,-1)
	            // This page is way off-screen to the left.
	            view.setAlpha(0);

	        } else if (position <= 1) { // [-1,1]
	            // Modify the default slide transition to shrink the page as well
	            float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
	            float vertMargin = pageHeight * (1 - scaleFactor) / 2;
	            float horzMargin = pageWidth * (1 - scaleFactor) / 2;
	            if (position < 0) {
	                view.setTranslationX(horzMargin - vertMargin / 2);
	            } else {
	                view.setTranslationX(-horzMargin + vertMargin / 2);
	            }

	            // Scale the page down (between MIN_SCALE and 1)
	            view.setScaleX(scaleFactor);
	            view.setScaleY(scaleFactor);

	            // Fade the page relative to its size.
	            view.setAlpha(MIN_ALPHA +
	                    (scaleFactor - MIN_SCALE) /
	                    (1 - MIN_SCALE) * (1 - MIN_ALPHA));

	        } else { // (1,+Infinity]
	            // This page is way off-screen to the right.
	            view.setAlpha(0);
	        }
	    }
	}
	
	public class DepthPageTransformer implements ViewPager.PageTransformer {
	    private static final float MIN_SCALE = 0.75f;

	    
	    @Override
	    public void transformPage(View view, float position) {
	        int pageWidth = view.getWidth();

	        if (position < -1) { // [-Infinity,-1)
	            // This page is way off-screen to the left.
	            view.setAlpha(0);

	        } else if (position <= 0) { // [-1,0]
	            // Use the default slide transition when moving to the left page
	            view.setAlpha(1);
	            view.setTranslationX(0);
	            view.setScaleX(1);
	            view.setScaleY(1);

	        } else if (position <= 1) { // (0,1]
	            // Fade the page out.
	            view.setAlpha(1 - position);

	            // Counteract the default slide transition
	            view.setTranslationX(pageWidth * -position);

	            // Scale the page down (between MIN_SCALE and 1)
	            float scaleFactor = MIN_SCALE
	                    + (1 - MIN_SCALE) * (1 - Math.abs(position));
	            view.setScaleX(scaleFactor);
	            view.setScaleY(scaleFactor);

	        } else { // (1,+Infinity]
	            // This page is way off-screen to the right.
	            view.setAlpha(0);
	        }
	    }

		
	}
	
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//	  //Handle the back button
//	  if (keyCode == KeyEvent.KEYCODE_BACK) {
//	    //Ask the user if they want to quit
////	    new AlertDialog.Builder(this)
////	      .setIcon(android.R.drawable.ic_dialog_alert)
////	      .setTitle("Exit")
////	      .setMessage("Are you sure you want to leave?")
////	      .setNegativeButton(android.R.string.cancel, null)
////	      .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
////	      
////	        public void onClick(DialogInterface dialog, int which){
////	          // Exit the activity
////	          NewsActivity.this.finish();
////	        }
////	      })
////	      .show();
//	    
//	    	
//	    	//if(exit){
//	    //		 NewsActivity.this.finish();
//	    	//	 System.gc();
//	    		
////	    	}
////	    	else{
////	    		Toast.makeText(this,getResources().getString(R.string.news_activity_exit), Toast.LENGTH_LONG).show();
////	    	}
////	    	this.exit = !this.exit;
//
//	    // Say that we've consumed the event
//	    return true;
//	  }
//
//	  return super.onKeyDown(keyCode, event);
//	} 
	
	

	@Override
	protected void onSaveInstanceState(Bundle outState) {
	//	outState.putParcelableArrayList(NewsActivity.KEY_NEWS_LIST_ARRAY,
		//		parNewsListArray);
		outState.putInt(NewsActivity.KEY_HEIGHT_ACTION_BAR,
				this.heightActionBar);
		super.onSaveInstanceState(outState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		try{
			getMenuInflater().inflate(R.menu.newactivity_menu, menu);
	
			MenuItem rateMenuItem = menu.add(Menu.NONE, R.id.action_rate, Menu.NONE, R.string.action_rate);
			rateMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			Drawable iconRate = getResources().getDrawable(R.drawable.ic_thumbs_up);
			
			MenuItem shareMenuItem = menu.add(Menu.NONE, R.id.action_share,
					Menu.NONE, R.string.action_share);
			shareMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			Drawable iconShare = getResources().getDrawable(android.R.drawable.ic_menu_share);
			ShareActionProvider actionProvider = new ShareActionProvider(this);
			
			actionProvider.setShareHistoryFileName("newsactivity_share.xml");
			actionProvider.setShareIntent(getDefaultShareIntent());
			actionProvider.setOnShareTargetSelectedListener(this);
			
			shareMenuItem.setActionProvider(actionProvider);
			
			// FIXME: getAction().getHeight get null when rotate screen Android
			// 4.1.2
			if (getActionBar().getHeight() != 0) {
				this.heightActionBar = getActionBar().getHeight();
			}
	
			rateMenuItem.setIcon(ViewUtils.scaleImage(
					iconRate, this.heightActionBar));
			shareMenuItem.setIcon(ViewUtils.scaleImage(
					iconShare, this.heightActionBar));
		
			return super.onCreateOptionsMenu(menu);
		}
		catch(Exception e){
			LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
			
		}
		return false;
	}

	  private Intent getDefaultShareIntent(){
		  try {
	        Intent intent = new Intent(Intent.ACTION_SEND);
	        intent.setType("text/plain");
	        intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
	        	        
	    	NewsItem item = this.parNewsListArray.get(this.pager.getCurrentItem());
			String message = 
					String.format("%s\n%s" +
						"\n\n" +
						"%s\n" +
						"%s\n" +
						"%s", 
						 getString(R.string.app_name),
						WidgetApplication.MARKET_LINK,
						item.getTitle(), TimeDateUtils.getDateStringFromNormalTimestamp(item.getPubdate(), "dd MMM yyyy HH:mm:ss", new Locale(AppManager.getLocaleManager().getCurrentServerLang())), item.getLink());
			
			intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_with_help) + " "+ getString(R.string.app_name));
			intent.putExtra(Intent.EXTRA_TEXT, message);
		   
			LogManager.LogV(NewsActivity.className, LogManager.getExecuteMethodName(), intent, message);
	        
	        return intent;
		  } catch (NumberFormatException e) {
				LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
				
			
			} catch (Exception e) {
				LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
				
				
			}
		  return null;
	    }
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		updatePagerText();
		switch (item.getItemId()) {

		case R.id.action_rate:
			Intent goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse(WidgetApplication.MARKET_URI));
			startActivity(goToMarket);
		
			return true;
		
		}
		return super.onOptionsItemSelected(item);
	}

	private void updatePagerText() {
			pageText.setText(String.format("%s / %s",
			pager.getCurrentItem() + 1, pagerAdapter.getCount()));
	}

	private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
		ArrayList<NewsItem> newsArrayList;
	
		public ScreenSlidePagerAdapter(
				android.support.v4.app.FragmentManager fragmentManager,
				ArrayList<NewsItem> items) {
			super(fragmentManager);
			this.newsArrayList = items;
			
		}

		@Override
		public android.support.v4.app.Fragment getItem(int position) {
			NewsPage fragment =  com.icebergteam.warfacewidget.news.ui.NewsPage
					.create(position, this.newsArrayList.get(position), NewsActivity.this);
	
			return fragment;
		}

		
		@Override
		public int getCount() {
			return this.newsArrayList.size();
		}
	}

	@Override
	public boolean onShareTargetSelected(ShareActionProvider source,
			Intent intent) {
		source.setShareIntent(getDefaultShareIntent());
	
		return false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		WidgetProvider.refreshWidget(getIntent());
	}
}